<script setup lang="ts">
import { ref, reactive } from 'vue'
import { onLoad, onPageScroll } from '@dcloudio/uni-app'
import QNav from '@/components/q-nav/q-nav.vue'
import ServeChat from '@/basePackage/pages/customerService/cmponents/serve-chat.vue'
import Expression from '@/basePackage/pages/customerService/expression/Index.vue'
import Auth from '@/components/auth/auth.vue'
import { pageScrollTo } from '@/libs/pageScrollTo'
import type { ChatMessage, ShopData, Message, CurrentProduct } from '@/basePackage/pages/customerService/types'
import { getMessages, sendMessages } from '@/apis/message/index'
import { useShopInfoStore } from '@/store/modules/shopInfo/index'

const $userStore = useShopInfoStore()
//控制显示隐藏的数据
const focus = ref(false)
const expressionPopup = ref(false)
const productPopupShow = ref(false)
//发送请求时候的页数 多少条数据
const pageConfig = reactive({
    pages: 1,
    current: 1,
    size: 10,
})
//控制加载中标识是否显示
const showLoading = ref(true)
//记录当前光标位置
const inputFocusIndex = ref(0)
//输入框的数据收集
const chatParams = ref<ChatMessage>({
    messageType: 'TEXT',
    message: '',
})
//聊天列表数据
const adminMessages = ref<Message[]>([])
//商家的数据
const shopData = reactive<ShopData>({
    useid: '',
    shopName: '',
    shopLogo: '',
})

onLoad((option: any) => {
    uni.$emit('updateTitle')
    //获取上个页面传递过来的useid
    shopData.useid = option.useid
    shopData.shopName = option.username
    shopData.shopLogo = option.useravatar
    // 获取客服聊天列表
    handleGetMessageList()
    // 渲染完毕后，设置页面滚动到底部
    pageScrollTo()
})

/**
 * 收集输入框的数据 发送消息
 */
const handleSendChat = async () => {
    if (!chatParams.value.message) {
        return
    }
    const { message, messageType } = chatParams.value
    const query = {
        content: message,
        messageType,
        receiverId: shopData.useid,
        senderId: $userStore.shopInfo.id,
    }
    const data = await sendMessages(query)
    handleGetMessageList()
    pageScrollTo()
    if (data.code !== 200) {
        uni.showToast({
            title: '发送失败',
            icon: 'none',
        })
    }
    //清空输入框
    chatParams.value.message = ''
}
/**
 * 函数方法 页面下拉到底部
 */
onPageScroll(async ({ scrollTop }) => {
    if (scrollTop === 0) {
        try {
            showLoading.value = true
            // await initPigeonMessageShopChat(true)
            pageScrollTo(0)
        } catch (error) {
            error
        }
        showLoading.value = false
    }
})

/**
 * 获取聊天列表数据
 */
const handleGetMessageList = async (isLoad = false) => {
    if (!isLoad) {
        // 刷新
        pageConfig.current = 1
    } else if (isLoad && pageConfig.current < pageConfig.pages) {
        // 更新
        pageConfig.current++
    }
    const data = await getMessages(shopData.useid, { ...pageConfig, shopId: $userStore.shopInfo.id })
    adminMessages.value = data.data.records
    //showLoading 加载中图标取消
    showLoading.value = false
}
/**
 * 失去焦点记录当前光标位置 用处 插入表情
 * @param {*} e
 */
const handleBlur = (e: any) => {
    focus.value = false
    // 记录当前光标位置
    inputFocusIndex.value = e.detail.cursor
}
/**
 * 插入表情
 * @param {*} val
 */
const handleInsertExpression = (val: string) => {
    let str = chatParams.value.message.substring(0, inputFocusIndex.value)
    chatParams.value.message = chatParams.value.message.replace(str, str + val)
    inputFocusIndex.value += val.length // 表情位置
    focus.value = true
}
/**
 * 发送图片
 */
const handleImageSend = () => {
    console.log('发送图片')
    uni.chooseImage({
        sourceType: ['album'],
        count: 1,
        success: (res) => {
            uni.uploadFile({
                url: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_UPLOAD_URL,
                filePath: res.tempFilePaths[0],
                name: 'file',
                success: (uploadFileRes) => {
                    const { data } = JSON.parse(uploadFileRes.data)
                    sendMessagesImage({ messageType: 'IMAGE', message: data })
                },
            })
        },
    })
}
const sendMessagesImage = async (params: ChatMessage) => {
    const { message, messageType } = params
    const query = {
        content: message,
        messageType,
        receiverId: shopData.useid,
        senderId: $userStore.shopInfo.id,
    }
    const data = await sendMessages(query)
    console.log(data)
    if (data.code !== 200) return uni.showToast({ title: '消息发送失败', icon: 'none' })
    handleGetMessageList()
    pageScrollTo()
}
</script>

<template>
    <q-nav :title="shopData.shopName" style="position: fixed" class="nav-container" />
    <view class="nav-container--place"></view>
    <view class="chat-container">
        <view class="chat-loading"><u-loading v-show="showLoading" mode="flower"></u-loading></view>
        <serve-chat :message="adminMessages" :shop-info="shopData" />
    </view>
    <!-- footer btn start -->
    <view class="chat-input-placeholder" :class="expressionPopup ? 'chat-expression' : ''" />
    <view class="chat-input" :class="expressionPopup ? 'chat-expression' : ''">
        <!-- <product-popup v-if="currentProductInfo.id && productPopupShow" :info="currentProductInfo" @send-click="handleSendProduct" /> -->
        <view class="chat-input__container" @click="productPopupShow = false">
            <view class="chat-input--input">
                <input
                    v-model.trim="chatParams.message"
                    :focus="focus"
                    placeholder="请输入内容"
                    confirm-type="search"
                    @blur="handleBlur"
                    @confirm="handleSendChat"
                />
            </view>
            <view class="chat-input--send">
                <u-icon name="server-man" size="20px" @click="expressionPopup = !expressionPopup"></u-icon>
            </view>
            <view class="chat-input--send" @click="handleImageSend">
                <u-icon name="plus-circle" size="20px"></u-icon>
            </view>
            <view class="chat-input--send">
                <u-button type="error" shape="circle" size="mini" :disabled="!chatParams.message.length" @click="handleSendChat">发送</u-button>
            </view>
        </view>
        <expression @expression-select="handleInsertExpression" />
    </view>
    <!-- footer btn end -->
    <Auth />
</template>

<style scoped lang="scss">
@include b(place) {
    height: 300rpx;
    background: #000;
}
@include b(nav-container) {
    top: 0;
    left: 0;
    right: 0;
    height: 80rpx;
    background: fff;
    z-index: 99;
    @include m(place) {
        height: 80rpx;
    }
}
@include b(chat-container) {
    padding: 10rpx;
}
@include b(chat-input-placeholder) {
    height: 100rpx;
}
@include b(chat-input) {
    position: fixed;
    height: 100rpx;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 99;
    background: #fff;
    padding: 0 20rpx;
    @include e(container) {
        @include flex;
        justify-content: space-between;
        align-items: center;
        height: 100rpx;
    }
    @include m(send) {
        padding: 10rpx;
        border-radius: 50%;
    }
    @include m(input) {
        width: 500rpx;
        border: 1rpx solid #ccc;
        padding: 10rpx;
        border-radius: 10rpx;
    }
}
@include b(chat-loading) {
    text-align: center;
    height: 60rpx;
    line-height: 60rpx;
}
@include b(chat-expression) {
    height: 500rpx;
    align-items: flex-start;
}
</style>
